package com.ktjy.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ktjy.dto.DictDataDTO;
import com.ktjy.mapper.SysDictDataMapper;
import com.ktjy.pojo.SysDictData;
import com.ktjy.service.SysDictDataService;
import com.ktjy.utils.AjaxResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api/sys/dictData")
@Tag(name = "字典模块")
public class SysDictDataController {
    @Resource
    SysDictDataService sysDictDataService;
    @Resource
    SysDictDataMapper sysDictDataMapper;

    /**
     * 查询字典数据列表 分页
     */
    @GetMapping("/list")
    @Operation(summary = "字典数据列表接口")
    public AjaxResult list(SysDictData sysDictData,
                           @Parameter(description = "页码数") @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                           @Parameter(description = "每页显示条数") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {

        IPage<SysDictData> page = sysDictDataService.getPage(sysDictData, pageNo, pageSize);
        return AjaxResult.success(page);
    }

    /**
     * 根据id查询字典数据
     */
    @GetMapping("/view/{id}")
    @Operation(summary = "根据id查询字典数据接口")
    public AjaxResult getById(@PathVariable("id") Long id) {
        SysDictData sysDictData = sysDictDataService.getSysDictDataById(id);
        return AjaxResult.success(sysDictData);
    }

    /**
     * 新增字典数据
     */
    @PostMapping("/add")
    @Operation(summary = "新增字典数据接口")
    public AjaxResult add(@RequestBody SysDictData sysDictData) {
        int insert = sysDictDataService.insert(sysDictData);
        return AjaxResult.success(insert);
    }

    /**
     * 修改字典数据
     */
    @PutMapping("/edit")
    @Operation(summary = "修改字典数据接口")
    public AjaxResult edit(@RequestBody SysDictData sysDictData) {
        int update = sysDictDataService.update(sysDictData);
        return AjaxResult.success(update);
    }

    /**
     * 删除字典数据
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除字典数据接口")
    public AjaxResult delete(@PathVariable("id") Long id) {
        int delete = sysDictDataService.delete(id);
        return AjaxResult.success(delete);
    }

    /**
     * 导出
     */
    @GetMapping("/export")
    @Operation(summary = "导出字典数据接口")
    public void export(HttpServletResponse response) {
        //查询需要导出的数据
        List<SysDictData> list = sysDictDataMapper.queryDictData();
        // 得到一个excel文件
        ExportParams exportParams = new ExportParams();
        exportParams.setTitle("字典数据");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, SysDictData.class, list);
        //输出流输出给浏览器
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        ServletOutputStream out = null;
        try {
            //设置下载文件名称
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("字典数据.xlsx", "UTF-8") + ".xlsx");
            out = response.getOutputStream();
            workbook.write(out);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (out != null)
                try {
                    out.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
        }
    }

    /**
     * 批量删除字典数据
     */
    @PostMapping("/deleteBatch")
    public AjaxResult deleteBatch(@RequestBody(required = false)List <Long> ids) {
        //参数校验
        if (ids == null || ids.size() == 0) {
            return AjaxResult.error("参数不能为空");
        }
        try{
            boolean success = sysDictDataService.deleteBatchIds(ids);
            return AjaxResult.success("删除成功"+(success? ids.size():0+"条数据"));
        }catch (Exception e){
            return AjaxResult.error("删除失败");
        }
    }

    //根据字典类型查询字典数据
    @GetMapping("/getDictData")
    @Operation(summary = "根据字典类型查询字典数据")
    @PreAuthorize("@ss.hasPerm('system:dict:query')") // 权限控制
    public AjaxResult getDictData(DictDataDTO dictDataDTO){
        List<SysDictData> list = sysDictDataService.getDictData(dictDataDTO);
        if (list != null){
            return AjaxResult.success("查询成功", list);
        }else {
            return AjaxResult.error("未查询到字典数据");
        }
    }
}
